package model;

import java.io.File;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class SQLAdapter{
	private DataSource dataSource;
	
	private Statement statement;
	private PreparedStatement preparedStatement;
	private ResultSet resultSet;
	
	public SQLAdapter(File configFile){
		dataSource = new DataSource(configFile);
	}
	
	public SQLAdapter(String driver, String protocol, String host, String database, String username, String password){
		dataSource = new DataSource(driver, protocol, host, database, username, password);
	}
	
	public DataSource getDataSource(){
		return dataSource;
	}
	
	public PreparedStatement getPreparedStatement(String sql) throws SQLException, NullPointerException{
		dataSource.startConnection();
		if(dataSource.getConnection() != null){
			preparedStatement = dataSource.getConnection().prepareStatement(sql);
		}else{
			throw new NullPointerException("Database connection is null");
		}
		
		return preparedStatement;
	}
	
	public int executeUpdateStatement(String sql) throws SQLException, NullPointerException{
		int result = -1;
		
		dataSource.startConnection();
		if(dataSource.getConnection() != null){
			statement = dataSource.getConnection().createStatement();
			result = statement.executeUpdate(sql);
			
			return result;
		}else{
			throw new NullPointerException("Database connection is null");
		}
	}
	
	public ResultSet executeQueryStatement(String sql) throws SQLException, NullPointerException{
		dataSource.startConnection();
		if(dataSource.getConnection() != null){
			statement = dataSource.getConnection().createStatement();
			resultSet = statement.executeQuery(sql);
			
			return resultSet;
		}else{
			throw new NullPointerException("Database connection is null");
		}		
    }
	
	public void close(){
		try{
			if(resultSet != null && !resultSet.isClosed()){
				resultSet.close();
			}if(statement != null && !statement.isClosed()){
				statement.close();
			}if(preparedStatement != null && !preparedStatement.isClosed()){
				preparedStatement.close();
			}
			dataSource.closeConnection();
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		SQLAdapter adapter = null;
		try{
			adapter = new SQLAdapter(new File("bd/bd_config.xml"));
			
			ResultSet rs = adapter.executeQueryStatement("SELECT a.acao FROM applog.acao a LIMIT 1000");
			while(rs.next()){
				System.out.println(rs.getString("a.acao"));
			}
		}catch(NullPointerException e){
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			if(adapter != null){
				adapter.close();
			}
		}
	}
}